package com.aerotechnic.dao.implementation;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.aerotechnic.dao.interfaces.VisiteDaoIn;
import com.aerotechnic.entities.Visite;

@Repository
public class VisiteDao implements VisiteDaoIn {

	@Autowired
	private SessionFactory sessionFactory;

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public void save(Visite t) {

		// TODO Auto-generated method stub

		getCurrentSession().save(t);

	}

	@Override
	public void delete(Long id) {
		// TODO Auto-generated method stub

		Visite e = findByID(id);
		if (e != null)
			getCurrentSession().delete(e);

	}

	@Override
	public Visite findByID(Long id) {
		// TODO Auto-generated method stub

		Session session = sessionFactory.getCurrentSession();

		return (Visite) session.createQuery("FROM Visite where id= " + id)
				.list().get(0);
	}

	@Override
	public void update(Visite t) {
		// TODO Auto-generated method stub

		getCurrentSession().update(t);
	}

	public List<Visite> findAll() {
		// TODO Auto-generated method stub

		return getCurrentSession().createQuery("from Visite v order by v.dateDebut desc").list();        
	}

	@Override
	public Visite getlastVisite() {
		// TODO Auto-generated method stub
		return (Visite) getCurrentSession()
				.createQuery(
						"from Visite v1 where id =(select max(id) from Visite v2)")   
				.list().get(0);                
	}

}
